package cn.cdzdjd.service.impl;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Service;

import cn.cdzdjd.constant.BrowserConstant;
import cn.cdzdjd.exception.ErrorCode;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.MeiTuanVideoService;
import cn.cdzdjd.util.JsonUtils;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.vo.VideoInfoVO;

@Service
public class MeiTuanVideoServiceImpl implements MeiTuanVideoService {
	private final String baseUrl = "https://contents.meituan.com/capi/shareinfo";
	@Override
	public VideoInfoVO getVideoInfo(String url) {
		try {
			Map<String, String> params = UrlUtil.convertUrlParamsToMap(new URL(url));
			Response response = Jsoup.connect(baseUrl).ignoreContentType(true).ignoreHttpErrors(true).followRedirects(false)
					.userAgent(BrowserConstant.USER_AGENT_PC).header("Accept", BrowserConstant.ACCEPT).referrer(baseUrl).method(Method.POST)
					.requestBody(JsonUtils.toJsonString(params)).header("Content-Type", "application/json")
					.execute();
			String jsonStr = response.body();
			JSONObject json = new JSONObject(jsonStr);
			JSONObject videoInfo = json.getJSONObject("data").getJSONObject("videoInfo");
			String videoTitle = videoInfo.getString("title");
			String posterUrl = videoInfo.getString("firstFrame");
			String videoUrl = videoInfo.getString("videoUrl");
			List<String> videoList = new ArrayList<>();
			videoList.add(UrlUtil.setHttps(videoUrl));
			List<String> posterList = new ArrayList<>();
			posterList.add(UrlUtil.setHttps(posterUrl));
			return new VideoInfoVO(videoList, posterList, videoTitle, null);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RenException(ErrorCode.PARSE_ERROR);
		}
	}
}
